package com.longnuoqi.mydoctor.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;

import com.amap.api.services.poisearch.PoiSearch;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.activity.NearbyPlaceActivity;
import com.longnuoqi.mydoctor.entity.Hospital;
import com.longnuoqi.mydoctor.entity.Store;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;


import java.util.ArrayList;
import java.util.List;


/**
 * Created by Lenovo on 2015/12/29.
 */
public class NearbyFragment extends Fragment {
    private Spinner searchSpinner;
    private ImageView searchBtn;
    private TextView watchlist;
    private String searchTxt;
    private String url;
    private String id;
    private LatLonPoint latLonPoint;
    private String title;
    private String address;

    private View view;
    private double longitude = 0;//经度
    private double latitude = 0;//纬度
    private LatLng latLng;

    private String country;
    private String province;
    private String city;
    private String district;
    private String road;
    private MapView mapView;
    private AMap amap;
    private PoiSearch.Query query;

    //声明AMapLocationClient类对象
    public AMapLocationClient mlocationClient = null;
    //声明mLocationOption对象,存放的都是定位的一些相关参数
    public AMapLocationClientOption mLocationOption = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    longitude = aMapLocation.getLongitude();
                    latitude = aMapLocation.getLatitude();
                    latLng = new LatLng(latitude, longitude);
                    city = aMapLocation.getCity();
                    country = aMapLocation.getCountry();
                    province = aMapLocation.getProvince();
                    city = aMapLocation.getCity();
                    district = aMapLocation.getDistrict();
                    road = aMapLocation.getRoad();
                    //重写地图中心
                    CameraPosition cp = amap.getCameraPosition();
                    CameraPosition cpnew = CameraPosition.fromLatLngZoom(latLng, cp.zoom);
                    CameraUpdate update = CameraUpdateFactory.newCameraPosition(cpnew);
                    amap.moveCamera(update);//将地图中心移动到当前位置
                    Marker geoMarker = amap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f));
                    geoMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                    geoMarker.setPosition(latLng);
                    geoMarker.setTitle("您的当前位置：");
                    geoMarker.setSnippet(province + city + district + road);
                } else {
                    Log.e("=============", aMapLocation.getErrorInfo());
                }


            }

        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.nearby_layout, container, false);
        initView();
        initLocationOption();
        mapView.onCreate(savedInstanceState);//一定要这句代码
        amap = mapView.getMap();//通过mapview来获取amap对象
        return view;
    }

    public void initView() {
        mapView = (MapView) view.findViewById(R.id.map);
        searchSpinner = (Spinner) view.findViewById(R.id.nearby_search_text);
        String[] search_array = new String[]{"请选择所要查询类型", "附近医院", "附近药店"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), R.layout.nearby_spinner_layout, search_array);
        searchSpinner.setAdapter(arrayAdapter);
        searchSpinner.setOnItemSelectedListener(onItemSelectedListener);

        searchBtn = (ImageView) view.findViewById(R.id.nearby_search_btn);
        watchlist = (TextView) view.findViewById(R.id.nearby_watchlist_txt);
        searchBtn.setOnClickListener(onClickListener);
        watchlist.setOnClickListener(onClickListener);
    }

    public void initLocationOption() {
        mlocationClient = new AMapLocationClient(getActivity());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.setLocationListener(mLocationListener);
        //启动定位
        mlocationClient.startLocation();
    }

    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String unit = parent.getItemAtPosition(position).toString();
            switch (unit) {
                case "请选择所要查询类型":
                    searchTxt = "请选择所要查询类型";
                    break;
                case "附近医院":
                    searchTxt = "附近医院";
                    url = "http://www.tngou.net/api/hospital/location?x=" + longitude + "&y=" + latitude + "&rows=10";
                    break;
                case "附近药店":
                    searchTxt = "附近药店";
                    url = "http://www.tngou.net/api/store/location?x=" + longitude + "&y=" + latitude + "&rows=10";
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            searchTxt = "附近医院";
            url = "http://www.tngou.net/api/hospital/location?x=" + longitude + "&y=" + latitude;
        }
    };


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.nearby_search_btn:
                    if (searchTxt.equals("请选择所要查询类型")) {
                        Toast.makeText(getActivity(), "请选择查询内容!", Toast.LENGTH_SHORT).show();
                    } else {
                        searchNearby();
                    }
                    break;
                case R.id.nearby_watchlist_txt:
                    if (latitude == 0 || longitude == 0) {
                        Toast.makeText(getActivity(), "正在定位！请稍后查看！", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(getActivity(), NearbyPlaceActivity.class);
                        intent.putExtra("latitude", latitude);
                        intent.putExtra("longitude", longitude);
                        startActivityForResult(intent, 0);
                    }
                    break;
                default:
                    break;
            }

        }
    };

    private void searchNearby() {
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                ArrayList<PoiItem> pois = new ArrayList<>();
                if (searchTxt.equals("附近医院")) {
                    List<Hospital> hospitals = FileUtil.jsonHospitalList(s);
                    for (int i = 0; i < hospitals.size(); i++) {
                        Hospital hospital = hospitals.get(i);
                        id = hospital.getId() + "";
                        latLonPoint = new LatLonPoint(hospital.getY(), hospital.getX());
                        title = hospital.getName();
                        address = "地址：" + hospital.getAddress();
                        PoiItem poiItem = new PoiItem(id, latLonPoint, title, address);
                        pois.add(poiItem);
                    }
                } else if (searchTxt.equals("附近药店")) {
                    List<Store> stores = FileUtil.jsonStoreList(s);
                    Log.e("================", "Store list:" + stores.get(0).getName());
                    for (int i = 0; i < stores.size(); i++) {
                        Store store = stores.get(i);
                        id = store.getId() + "";
                        latLonPoint = new LatLonPoint(store.getY(), store.getX());
                        title = store.getName();
                        address = "地址：" + store.getAddress();
                        PoiItem poiItem = new PoiItem(id, latLonPoint, title, address);
                        pois.add(poiItem);
                    }
                }
                Log.e("====================", "url:" + url);
                Log.e("====================", "pois.size:" + pois.size());
                Log.e("====================", "pois.title:" + pois.get(0).getTitle());
                Log.e("====================", "pois.title:" + pois.get(1).getTitle());
                if (pois.size() > 0) {
                    PoiOverlay poiOverlay = new PoiOverlay(amap, pois);
                    poiOverlay.addToMap();
                    poiOverlay.zoomToSpan();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        queue.add(request);
    }

    //一定要重写Activity或Fragment对应的生命周期，因为地图属于第三方的提供，不会默认跟随android生命周期进行运作
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mlocationClient.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

}
